package com.example.handheld4_gsignal_app;

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.example.handheld4_gsignal_app.services.LocationService;
import com.example.handheld4_gsignal_app.services.NetworkService;
import com.example.handheld4_gsignal_app.services.SignalService;
import com.example.handheld4_gsignal_app.data.SignalData;

/**
 * 信号采集Activity - 专门的信号采集界面
 */
public class SignalCollectionActivity extends AppCompatActivity {

    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1001;
    
    private TextView signalStrengthText;
    private Button startCollectionButton;
    private Button backButton;
    
    private SignalService signalService;
    private LocationService locationService;
    private NetworkService networkService;
    private boolean isCollecting = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_signal_collection);
        
        initViews();
        setupClickListeners();
        initServices();
        checkPermissions();
    }

    /**
     * 初始化视图组件
     */
    private void initViews() {
        signalStrengthText = findViewById(R.id.signal_strength_text);
        // 注意：布局文件中没有location_text, network_text, status_text这些ID
        // 使用实际存在的ID
        startCollectionButton = findViewById(R.id.btnCollectSignal);
        // 注意：布局文件中没有stop_collection_button，只有btnCollectSignal
        backButton = findViewById(R.id.back_button);
        
        // 初始状态 - 由于没有stop按钮，移除相关代码
    }

    /**
     * 设置点击事件监听器
     */
    private void setupClickListeners() {
        startCollectionButton.setOnClickListener(v -> {
            if (isCollecting) {
                stopCollection();
            } else {
                startCollection();
            }
        });
        backButton.setOnClickListener(v -> finish());
    }

    /**
     * 初始化服务
     */
    private void initServices() {
        signalService = new SignalService(this);
        locationService = new LocationService(this);
        networkService = new NetworkService(this);
    }

    /**
     * 检查权限
     */
    private void checkPermissions() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) 
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, 
                new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 
                LOCATION_PERMISSION_REQUEST_CODE);
        } else {
            // 权限已获取，可以开始采集
            Toast.makeText(this, "权限已获取，准备就绪", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 权限请求结果处理
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "权限已获取，准备就绪", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "需要位置权限才能进行信号采集", Toast.LENGTH_LONG).show();
            }
        }
    }

    /**
     * 开始采集
     */
    private void startCollection() {
        if (!isCollecting) {
            isCollecting = true;
            startCollectionButton.setText("停止采集");
            startCollectionButton.setBackgroundResource(R.drawable.button_secondary);
            
            // 开始信号采集
            signalService.startCollection(new SignalService.SignalCallback() {
                @Override
                public void onSignalUpdate(int strength, String location, String network) {
                    runOnUiThread(() -> {
                        signalStrengthText.setText("信号强度: " + strength + " dBm");
                        // 注意：布局文件中没有location_text和network_text，只更新信号强度
                    });
                }

                @Override
                public void onError(String error) {
                    runOnUiThread(() -> {
                        Toast.makeText(SignalCollectionActivity.this, "采集错误: " + error, Toast.LENGTH_SHORT).show();
                    });
                }
            });
        }
    }

    /**
     * 停止采集
     */
    private void stopCollection() {
        if (isCollecting) {
            isCollecting = false;
            signalService.stopCollection();
            startCollectionButton.setText("开始采集");
            startCollectionButton.setBackgroundResource(R.drawable.button_primary);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (signalService != null) {
            signalService.stopCollection();
        }
    }
}